﻿using System;
using System.Web.Mvc;
using DTcms.Common;

namespace DTcms.Web.Mvc.UI.Page
{
    public partial class oauth_login : BaseController
    {
        protected string turl = string.Empty;
        protected string redirect = string.Empty;//回传地址

        /// <summary>
        /// OnInit事件,检查用户是否已经登录
        /// </summary>
        public oauth_login()
        {
            turl = Utils.GetCookie(DTKeys.COOKIE_URL_REFERRER);
            if (string.IsNullOrEmpty(turl) || turl == System.Web.HttpContext.Current.Request.Url.ToString().ToLower())
            {
                turl = linkurl("usercenter", "index");
            }
            if (turl == "")
            {
                turl = DTRequest.GetQueryString("from");
            }
            if (IsUserLogin())
            {
                //自动登录,跳转URL
                redirect = turl;
                return;
            }
            //检查是否已授权
            if (System.Web.HttpContext.Current.Session["oauth_name"] == null || System.Web.HttpContext.Current.Session["oauth_access_token"] == null || System.Web.HttpContext.Current.Session["oauth_openid"] == null)
            {
                redirect = linkurl("error", "?msg=" + Utils.UrlEncode("登录失败，用户授权已过期，请重新登录！"));
                return;
            }
            Model.user_oauth oauthModel = new BLL.user_oauth().GetModel(System.Web.HttpContext.Current.Session["oauth_name"].ToString(), System.Web.HttpContext.Current.Session["oauth_openid"].ToString());
            if (oauthModel != null)
            {
                //检查用户是否存在
                Model.users model = new BLL.users().GetModel("user_name='"+ oauthModel.user_name + "' and status<3");
                if (model == null)
                {
                    redirect = linkurl("error", "?msg=" + Utils.UrlEncode("登录失败，授权用户不存在或已被删除！"));
                    return;
                }

                //记住登录状态，防止Session提前过期
                System.Web.HttpContext.Current.Session[DTKeys.SESSION_USER_INFO] = model;
                System.Web.HttpContext.Current.Session.Timeout = 45;

                Utils.WriteCookie(DTKeys.COOKIE_USER_NAME_REMEMBER, "DTcms", model.user_name);
                Utils.WriteCookie(DTKeys.COOKIE_USER_PWD_REMEMBER, "DTcms", model.password);
                //更新最新的Access Token
                oauthModel.oauth_access_token = System.Web.HttpContext.Current.Session["oauth_access_token"].ToString();
                new BLL.user_oauth().Update(oauthModel);

                //自动登录,跳转URL
                redirect = turl;
            }
        }
    }
}
